<template>
    <div>
        <el-breadcrumb separator-class="el-icon-caret-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区-->
        <el-card>
            <el-alert title="注意：只允许为第三方分类设置相关的参数" type="warning" show-icon :closable="false">
            </el-alert>
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品的分类: </span>
                    <el-cascader
                            v-model="selectedKeys"
                            :options="cateList"
                            :props="CascaderProps"
                            @change="handleChange" clearable>
                    </el-cascader>
                </el-col>
            </el-row>

            <!--tab页-->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!--添加动态参数-->
                <el-tab-pane label="动态属性" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="setAddDialog = true">添加参数
                    </el-button>
                    <el-table stripe border :data="manyTableData">
                        <!--动态tab表格-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" @close="handleTagClose(i,scope.row)" closable :key="i">{{item}}</el-tag>
                                <!--输入文本框-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisiable"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <!--添加按钮-->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                           @click="showEditDialog(scope.row.attr_id)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                           @click="deleteParams(scope.row.attr_id)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!--添加静态属性-->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="setAddDialog = true">添加属性
                    </el-button>
                    <el-table stripe border :data="onlyTableData">
                        <!--动态tab表格-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" @close="handleTagClose(i,scope.row)" closable :key="i">{{item}}</el-tag>
                                <!--输入文本框-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisiable"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <!--添加按钮-->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                           @click="showEditDialog(scope.row.attr_id)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                           @click="deleteParams(scope.row.attr_id)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

        </el-card>

        <!--新增参数弹出框-->
        <el-dialog
                :title="titleText"
                :visible.sync="setAddDialog"
                width="50%"
                @close="addDialogClose">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                 <el-button @click="setAddDialog = false">取 消</el-button>
                 <el-button type="primary" @click="addFormConfirm">确 定</el-button>
            </span>
        </el-dialog>

        <!--编辑参数弹出框-->
        <el-dialog
                :title="'修改' + titleText"
                :visible.sync="setEditDialog"
                width="50%"
                @close="addDialogClose">
            <el-form :model="addForm" :rules="addFormRules" ref="editFormRef" label-width="120px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                 <el-button @click="setEditDialog = false">取 消</el-button>
                 <el-button type="primary" @click="editFormConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "params",
        data() {
            return {
                //商品分类列表
                cateList: [],

                //属性
                CascaderProps: {
                    expandTrigger: 'hover',
                    value: "cat_id",
                    label: "cat_name",
                    children: "children"
                },

                //级联选择框选中的数组
                selectedKeys: [],

                //被激活的页签的名称
                activeName: 'many',

                //静态属性的数据
                onlyTableData: [],

                //动态参数的数据
                manyTableData: [],

                //控制添加对话框的显示与隐藏
                setAddDialog: false,

                //添加参数的表单数据对象
                addForm: {},

                //校验规则
                addFormRules: {
                    attr_name: [
                        {required: true, trigger: 'blur', message: "参数名称不能为空"}
                    ]
                },

                //控制编辑对话框的显示
                setEditDialog: false,
            }
        },
        created() {
            this.getCateList();
        },
        computed: {
            isBtnDisable() {
                return this.selectedKeys.length !== 3;
            },
            cateId() {
                if (this.selectedKeys.length === 3) return this.selectedKeys[2];
                return null;
            },
            titleText() {
                if (this.activeName === "many") return "添加动态参数";
                return "添加静态属性"
            }
        },
        methods: {
            async getCateList() {
                const {data} = await this.$http.get(`categories`);
                if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                this.cateList = data.data;
            },

            //处理级联选择框变化时的事件
            handleChange() {
                this.getParamsData();
            },

            //Tab页签(也就是不同的参数页面的切换)点击事件的处理函数
            handleTabClick() {
                this.getParamsData();
            },

            //获取参数列表
            async getParamsData() {
                if (this.selectedKeys.length !== 3){
                    //清空所有的数据，防止切换CateId时没有清空下面的数据
                    this.manyTableData = [];
                    this.onlyTableData = [];
                    return this.selectedKeys = [];
                }
                //根据所选分类的Id,获取对应的参数
                const {data} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}});
                if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                data.data.forEach(item => {
                    //防止attr_vals为空字符串，需要设置为[]
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                    //控制文本框的显示以及隐藏
                    item.inputVisiable = false;
                    //文本框中输入的值
                    item.inputValue = "";
                });
                if (this.activeName === "many") {
                    this.manyTableData = data.data;
                } else {
                    this.onlyTableData = data.data;
                }
            },

            //监听添加对话框的关闭事件
            addDialogClose() {
                this.$refs.addFormRef.resetFields();
                this.addForm = {};
            },

            //监听添加属性按钮
            addFormConfirm() {
                this.$refs.addFormRef.validate(async valid => {
                    if (valid) {
                        const {data} = await this.$http.post(`categories/${this.cateId}/attributes`, {
                            attr_name: this.addForm.attr_name, attr_sel: this.activeName
                        });
                        if (data.meta.status !== 201) return this.$message.error(data.meta.msg);
                        this.$message.success('添加参数成功');
                        this.getParamsData();
                        this.setAddDialog = false;
                    }
                });
            },

            //显示编辑属性对话框
            async showEditDialog(attrId) {
                const {data} = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {params: this.activeName});
                if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                this.addForm = data.data;
                this.setEditDialog = true;
            },

            //点击按钮修改参数信息
            editFormConfirm() {
                this.$refs.editFormRef.validate(async valid => {
                    if (valid) {
                        const {data} = await this.$http.put(`categories/${this.cateId}/attributes/${this.addForm.attr_id}`, this.addForm);
                        if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                        this.getParamsData();
                        this.$message.success('保存成功');
                        this.setEditDialog = false;
                    }
                })
            },

            //点击删除按钮，删除对应的参数
            async deleteParams(attrId) {
                const result = await this.$confirm('您确认要删除该参数嘛', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'error'
                }).catch(err => err);
                if (result === 'cancel') return this.$message.info('取消删除');
                const {data} = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`);
                if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                this.getParamsData();
                this.$message.success('删除成功');
            },

            //文本框失去焦点或者按下enter时都会触发
            async handleInputConfirm(rowData) {
                if (rowData.inputValue.trim().length === 0) {
                    rowData.inputValue = "";
                    return rowData.inputVisiable = false;
                }
                rowData.attr_vals.push(rowData.inputValue.trim());
                rowData.inputValue = "";
                rowData.inputVisiable = false;
                this.saveAttrValues(rowData);
            },

            //点击按钮展示文本输入框
            showInput(rowData) {
                rowData.inputVisiable = true;
                //$nextTick 方法的作用就是当页面的元素被重新渲染后才会执行回调函数中的方法
                this.$nextTick(() => {
                    //让文本框自动获得焦点
                    this.$refs.saveTagInput.$refs.input.focus();
                })
            },

            //根据索引删除对应的标签
            handleTagClose(index,rowData){
                rowData.attr_vals.splice(index , 1);
                this.saveAttrValues(rowData);
            },

            //保存Attr_vals到数据库
            async saveAttrValues(rowData){
                const {data} = await this.$http.put(`categories/${this.cateId}/attributes/${rowData.attr_id}`, {
                    attr_name: rowData.attr_name,
                    attr_sel: rowData.attr_sel,
                    attr_vals: rowData.attr_vals.join(' ')
                });
                if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                this.$message.success('修改参数项成功');
            }
        }
    }
</script>

<style scoped lang="less">

    .cat_opt {
        margin: 15px 0;
    }

    .el-tag {
        margin: 10px;
    }

    .input-new-tag {
        width: 120px;
    }
</style>
